package com.newmuis.open.codeeval.easy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * CodeEval.com > Easy Challenges > Unique Elements
 * 
 * Description:
 * 
 * You are given a sorted list of numbers with duplicates. Print out the sorted list with duplicates
 * removed.
 * 
 * Input sample:
 * 
 * File containing a list of sorted integers, comma delimited, one per line. e.g.
 * 
 * 1,1,1,2,2,3,3,4,4
 * 2,3,4,5,5
 * 
 * Output sample:
 * 
 * Print out the sorted list with duplicates removed, one per line
 * e.g.
 * 
 * 1,2,3,4
 * 2,3,4,5
 * 
 * @author Jonathan Newmuis (jon@newmuis.com)
 * @category easy
 * 
 */
public class dupes {
	/**
	 * @param args should contain only one CLI argument: the path to an input file which specifies
	 *            the input in the defined format.
	 * @throws IOException if there is a problem reading the given input file.
	 */
	public static void main(final String[] args) throws IOException {
		// Verify input argument length.
		if (args.length < 1) {
			throw new RuntimeException("Must specify input file path.");
		} else if (args.length > 1) {
			throw new RuntimeException("Illegal input arguments specified.");
		}

		// Read file from specified path.
		final BufferedReader reader = new BufferedReader(new FileReader(new File(args[0])));
		String line;

		while ((line = reader.readLine()) != null) {
			// Parse the line into integers.
			final String[] elements = line.split(",");
			final StringBuilder listBuilder = new StringBuilder();
			Integer previousElement = null;

			for (int i = 0; i < elements.length; i++) {
				try {
					final int currentElement = Integer.parseInt(elements[i]);
					if (previousElement == null || currentElement > previousElement) {
						// Add the element to the list.
						listBuilder.append(currentElement);
						previousElement = currentElement;

						// Use comma as a delimiter, iff there are more (unique!) elements to find.
						if (!elements[i].equals(elements[elements.length - 1])) {
							listBuilder.append(",");
						}
					}
				} catch (final NumberFormatException e) {
					throw new RuntimeException("Input file contained non-numeric arguments.");
				}
			}

			// Output the contents of the buffer.
			System.out.println(listBuilder.toString());
		}
	}
}
